package com.websocket;

import com.service.SocketService;
import com.util.WebsocketUtil;
import lombok.extern.java.Log;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * @author ruiwen
 * @date 2024/11/13 11:41
 */
@Component
@ServerEndpoint(value = "/connect/{pcUniqueId}")
@Log
public class WebsocketHandler {

    /**
     * 连接事件，加入注解
     * @param pcUniqueId
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam(value = "pcUniqueId") String pcUniqueId, Session session) {
        log.info("[WebSocket连接成功]，机器ID: " + pcUniqueId);
        // 添加到session的映射关系中
        WebsocketUtil.addSession(pcUniqueId, session);
    }

    /**
     * 连接事件，加入注解
     * 用户断开链接
     *
     * @param pcUniqueId
     * @param session
     */
    @OnClose
    public void onClose(@PathParam(value = "pcUniqueId") String pcUniqueId, Session session) {
        log.info("[WebSocket连接断开]，机器ID: " + pcUniqueId);
        // 删除映射关系
        WebsocketUtil.removeSession(pcUniqueId);
    }

    /**
     * 当接收到用户上传的消息
     *
     * @param pcUniqueId
     * @param session
     */
    @OnMessage
    public void onMessage(@PathParam(value = "pcUniqueId") String pcUniqueId, Session session, String message) {
        log.info("机器ID: " + pcUniqueId + " 发送消息: " + message);
        // 直接广播
        WebsocketUtil.sendMessage(pcUniqueId,"pang");
    }

    /**
     * 处理用户活连接异常
     *
     * @param session
     * @param throwable
     */
    @OnError
    public void onError(Session session, Throwable throwable) {
        log.info("机器异常断开链接，原因： " + throwable.getMessage());
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        throwable.printStackTrace();
    }
}
